package com.zhaoben.springboot.controller;

import com.baidu.aip.nlp.AipNlp;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

@RestController
public class Doc2vecController {

        private static final String APP_ID = "32019787";
        private static final String API_KEY = "mzVfLVZzgHg5RIet7VgnQDm5";
        private static final String SECRET_KEY = "hvxeZZ8vH8RIlfwX5yuHjsZHhFgPWjLS";

        @RequestMapping("/doc2vecRequest")
        public static double doc2vec(){
            AipNlp client = new AipNlp(APP_ID, API_KEY, SECRET_KEY);
            // 设置请求头格式
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);

            String file1Path = "D:\\idearworkspace\\springboot\\springboot\\src\\main\\java\\com\\zhaoben\\springboot\\jobutil\\file1.txt"; // 第一个文本文件的路径
            String file2Path = "D:\\idearworkspace\\springboot\\springboot\\src\\main\\java\\com\\zhaoben\\springboot\\jobutil\\file2.txt"; // 第二个文本文件的路径

            String text1 = readFile(file1Path); // 读取第一个文本文件
            String text2 = readFile(file2Path); // 读取第二个文本文件

            JSONObject result = client.simnet(text1, text2, null);
            double similarityScore = result.getDouble("score");
            System.out.println("文本相似度得分为：" + similarityScore);
            return similarityScore;
        }
        public static void main(String[] args) {
            doc2vec();
        }

        private static String readFile(String filePath) {
            StringBuilder sb = new StringBuilder();
            try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } catch (Exception e) {
                System.err.println("读取文件 " + filePath + " 出错：" + e.getMessage());
            }
            return sb.toString();
        }
    }
